<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Cesium SVG 方向跟随地球</title>
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Cesium.js"></script>
    <link href="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        html, body, #cesiumContainer {
            width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
        }
        .control-panel {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(42, 42, 42, 0.9);
            padding: 15px;
            border-radius: 8px;
            color: white;
            font-family: Arial, sans-serif;
            max-width: 300px;
            z-index: 1000;
        }
        .control-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
        }
        input[type="range"] {
            width: 100%;
        }
        button {
            background: #4CAF50;
            border: none;
            color: white;
            padding: 8px 15px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
        }
        .value-display {
            font-size: 12px;
            color: #aaa;
            margin-top: 5px;
        }
        h3 {
            margin-top: 0;
            border-bottom: 1px solid #555;
            padding-bottom: 5px;
        }
    </style>
</head>
<body>
<div id="cesiumContainer"></div>
<div class="control-panel">
    <h3>SVG 方向控制</h3>
    <div class="control-group">
        <label for="pitch">俯仰角 (Pitch):</label>
        <input type="range" id="pitch" min="-180" max="180" value="0">
        <div class="value-display" id="pitch-value">0°</div>
    </div>
    <div class="control-group">
        <label for="roll">滚转角 (Roll):</label>
        <input type="range" id="roll" min="-180" max="180" value="0">
        <div class="value-display" id="roll-value">0°</div>
    </div>
    <div class="control-group">
        <label for="heading">航向角 (Heading):</label>
        <input type="range" id="heading" min="0" max="360" value="0">
        <div class="value-display" id="heading-value">0°</div>
    </div>
    <div class="control-group">
        <button id="resetBtn">重置方向</button>
        <button id="addSvgBtn">添加SVG图标</button>
    </div>
    <div class="control-group">
        <p style="font-size:12px; color:#aaa;">移动地图并观察SVG图标如何跟随地球表面方向</p>
    </div>
</div>

<script>
    // Cesium Ion access token (使用默认token，生产环境请使用自己的token)
    Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwNWY1NDhkNy00NDI4LTQyZWQtYTRmNS1iNGQ0MjMxNDIzZWMiLCJpZCI6MTU0NDA1LCJpYXQiOjE2ODk1NzY0ODl9.1zt09SfJKVhZNs-zzn3fN5pzpkrYEzatuDTZYviZx1I";

    // 初始化Cesium viewer
    const viewer = new Cesium.Viewer('cesiumContainer', {
        terrainProvider: Cesium.createWorldTerrain(),
        timeline: false,
        animation: false
    });

    // 设置初始相机位置
    viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(116.39, 39.9, 1000000), // 北京
        orientation: {
            heading: 0,
            pitch: -Math.PI/4,
            roll: 0
        }
    });

    // 创建SVG字符串
    function createSvgString(color = '#4CAF50') {
        return `
                <svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
                    <defs>
                        <radialGradient id="grad" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
                            <stop offset="0%" style="stop-color:${color};stop-opacity:1" />
                            <stop offset="100%" style="stop-color:#000000;stop-opacity:0.7" />
                        </radialGradient>
                    </defs>
                    <circle cx="32" cy="32" r="28" fill="url(#grad)" stroke="#ffffff" stroke-width="2"/>
                    <path d="M32 12 L38 28 L52 28 L40 38 L46 54 L32 44 L18 54 L24 38 L12 28 L26 28 Z"
                          fill="#FFD700" stroke="#FF8C00" stroke-width="1.5"/>
                </svg>
            `;
    }

    // 将SVG字符串转换为Canvas
    function svgToCanvas(svgString) {
        return new Promise((resolve) => {
            const canvas = document.createElement('canvas');
            canvas.width = 64;
            canvas.height = 64;
            const ctx = canvas.getContext('2d');

            const img = new Image();
            img.onload = function() {
                ctx.drawImage(img, 0, 0, 64, 64);
                resolve(canvas);
            };

            const blob = new Blob([svgString], {type: 'image/svg+xml'});
            img.src = URL.createObjectURL(blob);
        });
    }

    // 创建跟随地球方向的SVG图标
    async function createOrientedSvgPrimitive(longitude, latitude, height, color) {
        const svgString = createSvgString(color);
        const canvas = await svgToCanvas(svgString);

        // 获取位置
        const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);

        // 创建primitive
        const primitive = new Cesium.Primitive({
            geometryInstances: new Cesium.GeometryInstance({
                geometry: new Cesium.RectangleGeometry({
                    rectangle: Cesium.Rectangle.fromDegrees(
                        longitude - 0.5, latitude - 0.5,
                        longitude + 0.5, latitude + 0.5
                    ),
                    height: height,
                    vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
                }),
                id: 'svg-icon'
            }),
            appearance: new Cesium.EllipsoidSurfaceAppearance({
                aboveGround: false
            })
        });

        // 设置材质
        primitive.appearance.material = new Cesium.Material({
            translucent: true,
            fabric: {
                type: 'Image',
                uniforms: {
                    image: canvas
                }
            }
        });

        return primitive;
    }

    // 存储当前SVG primitives
    let svgPrimitives = [];

    // 添加初始SVG图标
    async function addInitialSvgIcons() {
        const positions = [
            { lon: 116.39, lat: 39.9, height: 0, color: '#4CAF50' },  // 北京
            { lon: -74.0, lat: 40.7, height: 0, color: '#2196F3' },   // 纽约
            { lon: 139.7, lat: 35.7, height: 0, color: '#FF5722' },   // 东京
            { lon: -0.1, lat: 51.5, height: 0, color: '#9C27B0' },    // 伦敦
        ];

        for (const pos of positions) {
            const primitive = await createOrientedSvgPrimitive(
                pos.lon, pos.lat, pos.height, pos.color
            );
            viewer.scene.primitives.add(primitive);
            svgPrimitives.push(primitive);
        }
    }

    // 初始化
    addInitialSvgIcons();

    // 控制面板交互
    document.getElementById('pitch').addEventListener('input', function(e) {
        const value = e.target.value;
        document.getElementById('pitch-value').textContent = value + '°';
        updateSvgOrientation();
    });

    document.getElementById('roll').addEventListener('input', function(e) {
        const value = e.target.value;
        document.getElementById('roll-value').textContent = value + '°';
        updateSvgOrientation();
    });

    document.getElementById('heading').addEventListener('input', function(e) {
        const value = e.target.value;
        document.getElementById('heading-value').textContent = value + '°';
        updateSvgOrientation();
    });

    document.getElementById('resetBtn').addEventListener('click', function() {
        document.getElementById('pitch').value = 0;
        document.getElementById('roll').value = 0;
        document.getElementById('heading').value = 0;
        document.getElementById('pitch-value').textContent = '0°';
        document.getElementById('roll-value').textContent = '0°';
        document.getElementById('heading-value').textContent = '0°';
        updateSvgOrientation();
    });

    document.getElementById('addSvgBtn').addEventListener('click', async function() {
        // 获取当前相机位置
        const cameraPosition = viewer.camera.position;
        const cartographic = Cesium.Cartographic.fromCartesian(cameraPosition);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude);
        const height = cartographic.height;

        // 随机颜色
        const colors = ['#4CAF50', '#2196F3', '#FF5722', '#9C27B0', '#FFC107'];
        const color = colors[Math.floor(Math.random() * colors.length)];

        const primitive = await createOrientedSvgPrimitive(longitude, latitude, height, color);
        viewer.scene.primitives.add(primitive);
        svgPrimitives.push(primitive);
    });

    // 更新SVG方向
    function updateSvgOrientation() {
        // 这里可以添加代码来更新SVG的方向
        // 注意：Cesium的Primitive API对方向控制有限
        // 实际应用中可能需要使用Entity API或自定义着色器
        console.log("方向参数已更新:", {
            pitch: document.getElementById('pitch').value,
            roll: document.getElementById('roll').value,
            heading: document.getElementById('heading').value
        });
    }
</script>
</body>
</html>